package com.hsgene.common.util.bean;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;

/**
 * 对象字节数组互转
 *
 * @author wxf
 * @date 2018/10/31 9:23
 **/
public class BeanUtils {

    /**
     * Log
     */
    private static final Logger LOGGER = LogManager.getLogger(BeanUtils.class);

    /**
     * 对象转byte
     *
     * @param object
     * @return
     */
    public static byte[] objectToBytes(Object object) {
        if (object == null) {
            return null;
        }
        byte[] bytes = null;
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = null;
        try {
            oo = new ObjectOutputStream(bo);
            oo.writeObject(object);
            oo.flush();
            bytes = bo.toByteArray();
        } catch (IOException e) {
            LOGGER.error("object to bytes is error...", e);
        } finally {
            closeIOStream(bo, oo);
        }
        return bytes;
    }

    /**
     * byte转object
     *
     * @param bytes
     * @return
     */
    public static Object bytesToObject(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        Object obj = null;
        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
        ObjectInputStream oi = null;
        try {
            oi = new ObjectInputStream(bi);
            obj = oi.readObject();
        } catch (Exception e) {
            LOGGER.error("bytes to object is error...", e);
        } finally {
            closeIOStream(bi, oi);
        }
        return obj;
    }

    private static void closeIOStream(Closeable... closeables) {
        try {
            if (closeables != null) {
                for (Closeable closeable : closeables) {
                    closeable.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
